<template>
  <div class="flex">
    <!-- 左侧分类树 -->
    <div class="w-1/4 mr-4">
      <ContentWrap>
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold">题库分类</h3>
          <el-button
            type="primary"
            size="small"
            @click="openCategoryForm('create')"
            v-hasPermi="['eval:question-category:create']"
          >
            <Icon icon="ep:plus" class="mr-1" />
            新增分类
          </el-button>
        </div>
        <el-tree
          ref="treeRef"
          :data="categoryTree"
          :props="{ children: 'children', label: 'categoryName', value: 'id' }"
          node-key="id"
          :expand-on-click-node="false"
          :highlight-current="true"
          @node-click="handleCategoryClick"
        >
          <template #default="{ data }">
            <div class="flex items-center justify-between w-full">
              <span>{{ data.categoryName }}</span>
              <div class="flex">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click.stop="openCategoryForm('update', data.id)"
                  v-hasPermi="['eval:question-category:update']"
                >
                  <Icon icon="ep:edit" />
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click.stop="handleDeleteCategory(data.id)"
                  v-hasPermi="['eval:question-category:delete']"
                >
                  <Icon icon="ep:delete" />
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </ContentWrap>
    </div>

    <!-- 右侧题目列表 -->
    <div class="flex-1">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="题目内容" prop="questionContent">
            <el-input
              v-model="queryParams.questionContent"
              placeholder="请输入题目内容"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="题目类型" prop="questionType">
            <el-select
              v-model="queryParams.questionType"
              placeholder="请选择题目类型"
              clearable
              class="!w-240px"
            >
              <el-option label="单选题" value="single" />
              <el-option label="多选题" value="multiple" />
              <el-option label="判断题" value="judge" />
              <el-option label="填空题" value="fill" />
              <el-option label="简答题" value="essay" />
            </el-select>
          </el-form-item>
          <el-form-item label="难度等级" prop="difficultyLevel">
            <el-select
              v-model="queryParams.difficultyLevel"
              placeholder="请选择难度等级"
              clearable
              class="!w-240px"
            >
              <el-option label="简单" :value="1" />
              <el-option label="中等" :value="2" />
              <el-option label="困难" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="题目状态" prop="questionStatus">
            <el-select
              v-model="queryParams.questionStatus"
              placeholder="请选择题目状态"
              clearable
              class="!w-240px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openQuestionForm('create')"
              v-hasPermi="['eval:question:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="info"
              plain
              @click="handleImport"
              v-hasPermi="['eval:question:import']"
            >
              <Icon icon="ep:upload" class="mr-5px" /> 导入
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['eval:question:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="mb-4">
        <el-col :span="6">
          <el-card>
            <div class="flex items-center">
              <div class="flex-1">
                <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
                <div class="text-gray-500">总题目数</div>
              </div>
              <Icon icon="ep:collection" class="text-4xl text-blue-600" />
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="flex items-center">
              <div class="flex-1">
                <div class="text-2xl font-bold text-green-600">{{ statistics.enabledCount || 0 }}</div>
                <div class="text-gray-500">启用题目</div>
              </div>
              <Icon icon="ep:check" class="text-4xl text-green-600" />
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="flex items-center">
              <div class="flex-1">
                <div class="text-2xl font-bold text-orange-600">{{ statistics.easyCount || 0 }}</div>
                <div class="text-gray-500">简单题目</div>
              </div>
              <Icon icon="ep:sunny" class="text-4xl text-orange-600" />
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="flex items-center">
              <div class="flex-1">
                <div class="text-2xl font-bold text-red-600">{{ statistics.hardCount || 0 }}</div>
                <div class="text-gray-500">困难题目</div>
              </div>
              <Icon icon="ep:moon" class="text-4xl text-red-600" />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="题目类型" align="center" prop="questionType" width="100">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.EVAL_QUESTION_TYPE" :value="scope.row.questionType" />
            </template>
          </el-table-column>
          <el-table-column label="题目内容" align="left" prop="questionContent" width="300" />
          <el-table-column label="分值" align="center" prop="questionScore" width="80" />
          <el-table-column label="难度等级" align="center" prop="difficultyLevel" width="100">
            <template #default="scope">
              <el-tag :type="getDifficultyTagType(scope.row.difficultyLevel)">
                {{ getDifficultyText(scope.row.difficultyLevel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="题目状态" align="center" prop="questionStatus" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.questionStatus === 1 ? 'success' : 'danger'">
                {{ scope.row.questionStatus === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openQuestionDetail(scope.row.id)"
                v-hasPermi="['eval:question:query']"
              >
                详情
              </el-button>
              <el-button
                link
                type="primary"
                @click="openQuestionForm('update', scope.row.id)"
                v-hasPermi="['eval:question:update']"
              >
                编辑
              </el-button>
              <el-dropdown @command="(command) => handleQuestionCommand(command, scope.row)">
                <el-button link type="primary">
                  更多<Icon icon="ep:arrow-down" class="ml-5px" />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy">
                      复制
                    </el-dropdown-item>
                    <el-dropdown-item command="toggle">
                      {{ scope.row.questionStatus === 1 ? '禁用' : '启用' }}
                    </el-dropdown-item>
                    <el-dropdown-item command="delete">
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </div>
  </div>

  <!-- 分类表单弹窗 -->
  <QuestionCategoryForm ref="categoryFormRef" @success="loadCategoryTree" />
  
  <!-- 题目表单弹窗 -->
  <QuestionForm ref="questionFormRef" @success="getList" />
  
  <!-- 题目详情弹窗 -->
  <QuestionDetail ref="questionDetailRef" />
  
  <!-- 导入弹窗 -->
  <QuestionImport ref="importRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalQuestionBankVO, 
  EvalQuestionBankPageReqVO,
  EvalQuestionCategoryVO,
  getQuestionBankPage, 
  deleteQuestionBank, 
  exportQuestionBank,
  getQuestionCategoryTree,
  deleteQuestionCategory,
  getQuestionBankStatistics,
  batchUpdateQuestionBankStatus
} from '@/api/eval/question'
import QuestionCategoryForm from './QuestionCategoryForm.vue'
import QuestionForm from './QuestionForm.vue'
import QuestionDetail from './QuestionDetail.vue'
import QuestionImport from './QuestionImport.vue'

/** 题库管理 */
defineOptions({ name: 'EvalQuestion' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalQuestionBankVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const categoryTree = ref<EvalQuestionCategoryVO[]>([]) // 分类树
const selectedCategoryId = ref<number>() // 选中的分类ID
const queryParams = reactive<EvalQuestionBankPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  categoryId: undefined,
  questionContent: undefined,
  questionType: undefined,
  difficultyLevel: undefined,
  questionStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.categoryId = selectedCategoryId.value
    const data = await getQuestionBankPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 加载统计数据
    await loadStatistics()
  } finally {
    loading.value = false
  }
}

/** 加载统计数据 */
const loadStatistics = async () => {
  try {
    statistics.value = await getQuestionBankStatistics()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

/** 加载分类树 */
const loadCategoryTree = async () => {
  try {
    categoryTree.value = await getQuestionCategoryTree()
  } catch (error) {
    console.error('加载分类树失败:', error)
  }
}

/** 分类点击事件 */
const handleCategoryClick = (data: EvalQuestionCategoryVO) => {
  selectedCategoryId.value = data.id
  queryParams.pageNo = 1
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedCategoryId.value = undefined
  handleQuery()
}

/** 分类表单操作 */
const categoryFormRef = ref()
const openCategoryForm = (type: string, id?: number) => {
  categoryFormRef.value.open(type, id)
}

/** 题目表单操作 */
const questionFormRef = ref()
const openQuestionForm = (type: string, id?: number) => {
  questionFormRef.value.open(type, id, selectedCategoryId.value)
}

/** 题目详情操作 */
const questionDetailRef = ref()
const openQuestionDetail = (id: number) => {
  questionDetailRef.value.open(id)
}

/** 导入操作 */
const importRef = ref()
const handleImport = () => {
  importRef.value.open()
}

/** 题目更多操作 */
const handleQuestionCommand = async (command: string, row: EvalQuestionBankVO) => {
  switch (command) {
    case 'copy':
      await handleCopyQuestion(row.id!)
      break
    case 'toggle':
      await handleToggleStatus(row.id!, row.questionStatus === 1 ? 0 : 1)
      break
    case 'delete':
      await handleDeleteQuestion(row.id!)
      break
  }
}

/** 复制题目 */
const handleCopyQuestion = async (id: number) => {
  // 实现复制逻辑
  message.success('复制成功')
}

/** 切换状态 */
const handleToggleStatus = async (id: number, status: number) => {
  try {
    await batchUpdateQuestionBankStatus([id], status)
    message.success('状态更新成功')
    await getList()
  } catch {}
}

/** 删除题目 */
const handleDeleteQuestion = async (id: number) => {
  try {
    await message.delConfirm()
    await deleteQuestionBank(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 删除分类 */
const handleDeleteCategory = async (id: number) => {
  try {
    await message.delConfirm()
    await deleteQuestionCategory(id)
    message.success(t('common.delSuccess'))
    await loadCategoryTree()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await exportQuestionBank(queryParams)
    download.excel(data, '题库.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取难度标签类型 */
const getDifficultyTagType = (level: number) => {
  const typeMap = { 1: 'success', 2: 'warning', 3: 'danger' }
  return typeMap[level] || ''
}

/** 获取难度文本 */
const getDifficultyText = (level: number) => {
  const textMap = { 1: '简单', 2: '中等', 3: '困难' }
  return textMap[level] || '未知'
}

/** 初始化 **/
onMounted(() => {
  loadCategoryTree()
  getList()
})
</script>
